package com.cloudsigns.factorymanager2.engineering.model;

import android.text.TextUtils;
import android.util.Log;

import com.cloudsigns.factorymanager2.MyApplicaton;
import com.cloudsigns.factorymanager2.cusenum.CommonEnum;
import com.cloudsigns.factorymanager2.engineering.bean.AccountInfoBean;
import com.cloudsigns.factorymanager2.engineering.utils.EngineeringUtil;
import com.cloudsigns.factorymanager2.project.utils.ConstantUtil;
import com.cloudsigns.factorymanager2.project.utils.ProjectUtil;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

/**
 * Created by tony on 2018/1/14.
 */

public class LoginModel implements ILoginModel {

    @Override
    public void login(final String username, final String password, final OnLoginListener loginListener) {
        new Thread(new Runnable() {
            public void run() {

                try {

                    HttpClient client = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(ProjectUtil.LOGIN_URL);

                    HttpResponse response;

                    // 添加http头信息
                    httpPost.addHeader(HTTP.CONTENT_TYPE, ConstantUtil.CONTENT_TYPE);

                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("accountId", username);
                    jsonObject.put("password", password);

                    StringEntity se = new StringEntity(jsonObject.toString(), HTTP.UTF_8);
                    httpPost.setEntity(se);

                    Log.e("request URL=",ProjectUtil.LOGIN);
                    Log.e("jsonObject=",jsonObject.toString());

//                    httpPost.addHeader("Content-Type", "application/json");
                   /*  httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");

                    List<NameValuePair> list = new ArrayList<NameValuePair>();
                    list.add(new BasicNameValuePair("accountId", "13800138000"));
                    list.add(new BasicNameValuePair("password", "987654321"));
                    httpPost.setEntity(new UrlEncodedFormEntity(list));
                   httpPost.setEntity(new HttpEntity() {
                        @Override
                        public boolean isRepeatable() {
                            return false;
                        }

                        @Override
                        public boolean isChunked() {
                            return false;
                        }

                        @Override
                        public long getContentLength() {
                            return 0;
                        }

                        @Override
                        public Header getContentType() {
                            return null;
                        }

                        @Override
                        public Header getContentEncoding() {
                            return null;
                        }

                        @Override
                        public InputStream getContent() throws IOException, IllegalStateException {
                            return null;
                        }

                        @Override
                        public void writeTo(OutputStream outputStream) throws IOException {

                        }

                        @Override
                        public boolean isStreaming() {
                            return false;
                        }

                        @Override
                        public void consumeContent() throws IOException {

                        }
                    });*/
                    //                    httpPost.setEntity(new StringEntity(json, "UTF-8"));

                    response = client.execute(httpPost);
                    String result = EntityUtils.toString(response.getEntity(), "UTF-8").trim();
                    Log.e("request=",result);
                    JSONObject json = new JSONObject(result);
                    String code = json.getString("code");
                    if (null != loginListener) {
                        //"token":"a2b2378f-210c-45a7-be5f-95a958ade900"
                        if (code.equals(EngineeringUtil.HTTP_SUCCESSED_COD)) {

                            MyApplicaton.getApplication().setToken(json.getString("token"));
                            JSONObject accountJson = json.getJSONObject("account");
                            AccountInfoBean accountInfoBean = new AccountInfoBean();
                            accountInfoBean.setId(accountJson.getString("id"));
                            accountInfoBean.setAccountId(accountJson.getString("accountId"));
                            accountInfoBean.setAccountName(accountJson.getString("accountName"));
                            accountInfoBean.setCompanyId(accountJson.getString("companyId"));
                            accountInfoBean.setCompanyName(accountJson.getString("companyName"));
                            accountInfoBean.setAvatar(accountJson.getString("avatar"));

                            String roleCategory = accountJson.getString("roleCategory");
                            if (!TextUtils.isEmpty(roleCategory)) {
                                if (roleCategory.equals("SUPER")) {
                                    accountInfoBean.setRoleCategory(CommonEnum.ROLECATEGORY.SUPER);
                                } else if (roleCategory.equals("MANAGER")) {
                                    accountInfoBean.setRoleCategory(CommonEnum.ROLECATEGORY.MANAGER);
                                } else if (roleCategory.equals("TEAM")) {
                                    accountInfoBean.setRoleCategory(CommonEnum.ROLECATEGORY.TEAM);
                                }
                            }
                            MyApplicaton.getApplication().setAccountInfoBean(accountInfoBean);
                            loginListener.loginSuccess();
                        } else {
                            String error_str = code;
                            error_str += "," + ConstantUtil.getErrorCode(code);
                            if (!json.isNull("error_str")) {
                                error_str += "," + json.getString("error_str");
                            }
                            loginListener.loginFailed(error_str);
                        }
                    }
//                    int statusCode = response.getStatusLine().getStatusCode();
//
//                    if (statusCode == HttpStatus.SC_OK) {
//                        String s = EntityUtils.toString(response.getEntity(), "UTF-8").trim();
//                    } else {
//                        String s = String.valueOf(statusCode);
//
//                    }
//
//                    String s = EntityUtils.toString(response.getEntity(), "UTF-8").trim();

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {

                }

            }
        }).start();
    }

    public interface OnLoginListener {
        void loginSuccess();

        void loginFailed(String desc);
    }


//    public static void httpPostWithJSON(HttpPost httpPost, String json) throws Exception {
//        httpPost.addHeader(HTTP.CONTENT_TYPE, ConstantUtil.CONTENT_TYPE);
//        StringEntity se = new StringEntity(json);
////        se.setContentType(CONTENT_TYPE_TEXT_JSON);
//        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
//        httpPost.setEntity(se);
//    }
}
